package cn.ppool.test.utils.db_util;

import lombok.extern.log4j.Log4j2;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Date;

@Transactional
@Log4j2
@Service
public class BaseDao<T extends BaseBean> {

    @Autowired
    @PersistenceContext
    protected EntityManager entityManager;

    //获取和当前线程绑定的Seesion
    public Session getSession() {
        return entityManager.unwrap(Session.class);
    }

    public void saveOrUpdate(T bean) {
        if (bean.getId() == null) {
            bean.setId(new Date().getTime());
            bean.setCreateTime(new Date());
        } else {
            bean.setUpdateTime(new Date());
        }
        getSession().saveOrUpdate(bean);
    }

    public void query(String sql){
        getSession().createNativeQuery(sql).executeUpdate();
    }


}
